<?php 
class GoodsModel extends Model{
	// 定义操作表名
	public $table = 'f_goods';
	// 自动验证
	public $validate =array(
		array('gname','nonull','商品名称不能为空',2,3),
		array('unit','nonull','技术单位不能为空',2,3),
		array('old_price','nonull','市场价不能为空',2,3),
		array('new_price','nonull','商城价不能为空',2,3),
		);
	// 自动添加
	public $auto = array(
		array('time','time','function',2,3),
		// array('gpic','_gpic','method',2,3)
		);
	// 自动添加图片
	// public function _gpic(){
	// 	// 如果有文件上传
	// 	if ($_FILES && $_FILES['gpic']['error'] != 4) {
	// 		// 调用上传类
	// 		$upload = new Upload;
	// 		$info = $upload->upload();
	// 		// 如果没错就反出图片地址
	// 		if (is_null($upload->error)) {
	// 			return $info[0]['path'];
	// 		}else{
	// 			// 否则赋值给error
	// 			$this->error = $upload->error;
	// 		}
			
	// 		// p($info);die;
	// 	}
	// }

	// 添加商品
	public function add_data(){
		// 触发自动验证和自动添加
		if (!$this->create()) {
			return false;
		}
		// 如果自动添加图片报错
		if ($this->error) {
			return false;
		}
		// 商品详情表自动验证
		$goodsDetail = K('Goods_detail');
		if (!$goodsDetail->create()) {
			$this->error = $goodsDetail->error;
			return false;
		}
		// 返回商品表的自增id
		$this->data['f_admin_aid'] = Q('session.aid');
		// 找到cid对应的分类
		$cid = Q('post.f_category_cid');
		// 找到分类所对应的类型id
		$tid = K('Category')->where("cid={$cid}")->getField('f_type_tid',true);
		$this->data['f_type_tid'] = $tid[0];
		$gid = $this->add();

		// 添加商品属性表数据
		$goodsAttr = K('Goods_attr');
		// 添加属性
		$attr = Q('post.attr');
		foreach ($attr as $k => $v) {
			$goodsAttr->data['f_goods_gid'] = $gid;
			$goodsAttr->data['f_type_attr_taid'] = $k;
			$goodsAttr->data['gavalue'] = $v;
			$goodsAttr->add();
		}
		// 添加规格
		$goodsSpec = $_POST['spec'];
		foreach ($goodsSpec as $ke => $va) {
			foreach ($va['tavalue'] as $key => $value) {
				$goodsAttr->data['f_type_attr_taid'] = $ke;
				$goodsAttr->data['f_goods_gid'] = $gid;
				$goodsAttr->data['gavalue']=$value;
				$goodsAttr->data['addmoney']=$va['added'][$key];
				$goodsAttr->add();
			}
		}

		// 添加商品详情表数据
		$pic = Q('post.big_pic');
		// 循环缩略图  三种尺寸
		$bpic = array();
		$mpic = array();
		$spic = array();
		// 原图循环出大图
		foreach ($pic as $v) {
			 $img = new Image();
			 $bpic[]=$img->thumb($v,'',800,800,2);
		}
		// 通过大图循环中图
		foreach ($bpic as $v) {
			 $img = new Image();
			 $mpic[]=$img->thumb($v,'',350,350,2);
		}
		// 通过中图循环小图
		foreach ($mpic as $v) {
			 $img = new Image();
			 $spic[]=$img->thumb($v,'',70,70,2);
		}
		$goodsDetail->data['small_pic'] = implode(',', $spic);
		$goodsDetail->data['middle_pic'] = implode(',', $mpic);
		$goodsDetail->data['big_pic'] = implode(',', $bpic);
		$goodsDetail->data['f_goods_gid'] = $gid;
		$goodsDetail->add();
		return true;

	}









}


















 ?>